<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤统计 - 考勤管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            padding: 30px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #667eea;
        }
        
        .header h1 {
            color: #667eea;
            font-size: 28px;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .back-btn:hover {
            background: #5a6268;
        }
        
        .section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .section-title {
            color: #667eea;
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
            font-size: 14px;
        }
        
        .form-group input, .form-group select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group input:disabled {
            background: #e9ecef;
            cursor: not-allowed;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            font-weight: bold;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #333;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card h3 {
            color: #667eea;
            font-size: 14px;
            margin-bottom: 10px;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: #333;
        }
        
        .stat-card .unit {
            font-size: 12px;
            color: #666;
        }
        
        .summary-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .summary-table th, .summary-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        .summary-table th {
            background: #667eea;
            color: white;
            font-weight: bold;
        }
        
        .summary-table tr:hover {
            background: #f8f9fa;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }
        
        .message.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            display: block;
        }
        
        .message.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            display: block;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        .user-bar {
            background: rgba(102, 126, 234, 0.1);
            padding: 10px 15px;
            border-radius: 10px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .user-bar span {
            color: #667eea;
            font-weight: bold;
        }
        
        .logout-btn {
            padding: 6px 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .logout-btn:hover {
            background: #5568d3;
        }
    </style>
    <script src="/js/auth.js"></script>
</head>
<body>
    <div class="container">
        <div class="user-bar">
            <span id="userInfo">👤 加载中...</span>
            <button class="logout-btn" onclick="logout()">🚪 退出</button>
        </div>
        
        <div class="header">
            <h1>📈 考勤统计管理</h1>
            <a href="index.html" class="back-btn">← 返回首页</a>
        </div>
        
        <div id="message" class="message"></div>
        
        <!-- 班次设置 Section -->
        <div class="section">
            <div class="section-title">
                <span>⏰ 班次设置</span>
                <div class="button-group">
                    <button class="btn btn-primary" onclick="loadShiftSetting()">🔄 刷新</button>
                    <button class="btn btn-success" id="saveShiftBtn" onclick="saveShiftSetting()">💾 保存设置</button>
                </div>
            </div>
            <div class="form-grid">
                <div class="form-group">
                    <label for="workStart">上班时间</label>
                    <input type="time" id="workStart" value="09:00">
                </div>
                <div class="form-group">
                    <label for="workEnd">下班时间</label>
                    <input type="time" id="workEnd" value="18:00">
                </div>
                <div class="form-group">
                    <label for="lateGraceMin">迟到容差(分钟)</label>
                    <input type="number" id="lateGraceMin" min="0" value="10">
                </div>
                <div class="form-group">
                    <label for="earlyGraceMin">早退容差(分钟)</label>
                    <input type="number" id="earlyGraceMin" min="0" value="10">
                </div>
                <div class="form-group">
                    <label for="effectiveDate">生效日期</label>
                    <input type="date" id="effectiveDate">
                </div>
            </div>
        </div>
        
        <!-- 统计查询 Section -->
        <div class="section">
            <div class="section-title">
                <span>📊 月度统计查询</span>
            </div>
            <div class="form-grid">
                <div class="form-group">
                    <label for="summaryEmployeeId">员工</label>
                    <select id="summaryEmployeeId">
                        <option value="">请选择员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="summaryMonth">统计月份</label>
                    <input type="month" id="summaryMonth">
                </div>
                <div class="form-group" style="display: flex; align-items: flex-end;">
                    <div class="button-group">
                        <button class="btn btn-primary" onclick="loadSummary()">🔍 查询统计</button>
                        <button class="btn btn-warning" onclick="rebuildSummary()">🔄 重新计算</button>
                        <button class="btn btn-success" onclick="exportCSV()">📥 导出CSV</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 统计结果 -->
        <div id="summaryResult" style="display: none;">
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>出勤天数</h3>
                    <div class="number" id="workDays">0</div>
                    <div class="unit">天</div>
                </div>
                <div class="stat-card">
                    <h3>迟到次数</h3>
                    <div class="number" id="lateCount">0</div>
                    <div class="unit">次</div>
                </div>
                <div class="stat-card">
                    <h3>早退次数</h3>
                    <div class="number" id="earlyCount">0</div>
                    <div class="unit">次</div>
                </div>
                <div class="stat-card">
                    <h3>旷工次数</h3>
                    <div class="number" id="absentCount">0</div>
                    <div class="unit">次</div>
                </div>
                <div class="stat-card">
                    <h3>请假时长</h3>
                    <div class="number" id="leaveHours">0</div>
                    <div class="unit">小时</div>
                </div>
                <div class="stat-card">
                    <h3>加班时长</h3>
                    <div class="number" id="otHours">0</div>
                    <div class="unit">小时</div>
                </div>
                <div class="stat-card">
                    <h3>出差天数</h3>
                    <div class="number" id="travelDays">0</div>
                    <div class="unit">天</div>
                </div>
            </div>
            
            <table class="summary-table">
                <thead>
                    <tr>
                        <th>员工工号</th>
                        <th>员工姓名</th>
                        <th>统计月份</th>
                        <th>出勤天数</th>
                        <th>迟到次数</th>
                        <th>早退次数</th>
                        <th>旷工次数</th>
                        <th>请假(小时)</th>
                        <th>加班(小时)</th>
                        <th>出差(天)</th>
                    </tr>
                </thead>
                <tbody id="summaryTableBody">
                    <tr>
                        <td colspan="10" class="loading">暂无数据</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
        let employees = [];
        let currentSummary = null;
        let currentShiftId = null;
        
        // 页面加载时初始化
        window.addEventListener('load', () => {
            loadEmployees();
            loadShiftSetting();
            setDefaultMonth();
        });
        
        // 设置默认月份为当月
        function setDefaultMonth() {
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            document.getElementById('summaryMonth').value = `${year}-${month}`;
            
            const today2 = new Date();
            const year2 = today2.getFullYear();
            const month2 = String(today2.getMonth() + 1).padStart(2, '0');
            const day = String(today2.getDate()).padStart(2, '0');
            document.getElementById('effectiveDate').value = `${year2}-${month2}-${day}`;
        }
        
        // 加载员工列表
        async function loadEmployees() {
            try {
                const response = await fetch('/api/employees');
                const result = await response.json();
                
                if (result.code === 200) {
                    employees = result.data;
                    
                    const select = document.getElementById('summaryEmployeeId');
                    select.innerHTML = '<option value="">请选择员工</option>';
                    
                    employees.forEach(emp => {
                        const option = new Option(`${emp.empNo} - ${emp.name}`, emp.id);
                        select.add(option);
                    });
                }
            } catch (error) {
                console.error('加载员工列表失败:', error);
            }
        }
        
        // 加载班次设置
        async function loadShiftSetting() {
            try {
                const response = await fetch('/api/shift-setting/current');
                const result = await response.json();
                
                if (result.code === 200) {
                    const shift = result.data;
                    currentShiftId = shift.id;
                    
                    document.getElementById('workStart').value = shift.workStart.substring(0, 5);
                    document.getElementById('workEnd').value = shift.workEnd.substring(0, 5);
                    document.getElementById('lateGraceMin').value = shift.lateGraceMin;
                    document.getElementById('earlyGraceMin').value = shift.earlyGraceMin;
                    
                    if (shift.effectiveDate) {
                        const date = new Date(shift.effectiveDate);
                        const year = date.getFullYear();
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        document.getElementById('effectiveDate').value = `${year}-${month}-${day}`;
                    }
                    
                    showMessage('班次设置加载成功', 'success');
                } else {
                    showMessage('加载班次设置失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('加载班次设置失败: ' + error.message, 'error');
            }
        }
        
        // 保存班次设置
        async function saveShiftSetting() {
            const shiftData = {
                id: currentShiftId,
                workStart: document.getElementById('workStart').value + ':00',
                workEnd: document.getElementById('workEnd').value + ':00',
                lateGraceMin: parseInt(document.getElementById('lateGraceMin').value),
                earlyGraceMin: parseInt(document.getElementById('earlyGraceMin').value),
                effectiveDate: document.getElementById('effectiveDate').value
            };
            
            try {
                const response = await fetch('/api/shift-setting', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(shiftData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    currentShiftId = result.data.id;
                    showMessage('班次设置保存成功', 'success');
                } else {
                    showMessage('保存失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'error');
            }
        }
        
        // 加载统计
        async function loadSummary() {
            const empId = document.getElementById('summaryEmployeeId').value;
            const month = document.getElementById('summaryMonth').value;
            
            if (!empId) {
                showMessage('请选择员工', 'error');
                return;
            }
            
            if (!month) {
                showMessage('请选择月份', 'error');
                return;
            }
            
            try {
                const response = await fetch(`/api/summary?empId=${empId}&month=${month}`);
                const result = await response.json();
                
                if (result.code === 200) {
                    currentSummary = result.data;
                    displaySummary(currentSummary);
                    showMessage('统计加载成功', 'success');
                } else {
                    showMessage('加载统计失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('加载统计失败: ' + error.message, 'error');
            }
        }
        
        // 显示统计结果
        function displaySummary(summary) {
            document.getElementById('summaryResult').style.display = 'block';
            
            // 更新统计卡片
            document.getElementById('workDays').textContent = summary.workDays || 0;
            document.getElementById('lateCount').textContent = summary.lateCount || 0;
            document.getElementById('earlyCount').textContent = summary.earlyCount || 0;
            document.getElementById('absentCount').textContent = summary.absentCount || 0;
            document.getElementById('leaveHours').textContent = summary.leaveHours || 0;
            document.getElementById('otHours').textContent = summary.otHours || 0;
            document.getElementById('travelDays').textContent = summary.travelDays || 0;
            
            // 更新表格
            const tbody = document.getElementById('summaryTableBody');
            tbody.innerHTML = `
                <tr>
                    <td><strong>${summary.empNo || '-'}</strong></td>
                    <td>${summary.employeeName || '-'}</td>
                    <td>${summary.month}</td>
                    <td>${summary.workDays || 0}</td>
                    <td>${summary.lateCount || 0}</td>
                    <td>${summary.earlyCount || 0}</td>
                    <td>${summary.absentCount || 0}</td>
                    <td>${summary.leaveHours || 0}</td>
                    <td>${summary.otHours || 0}</td>
                    <td>${summary.travelDays || 0}</td>
                </tr>
            `;
        }
        
        // 重新计算统计
        async function rebuildSummary() {
            const empId = document.getElementById('summaryEmployeeId').value;
            const month = document.getElementById('summaryMonth').value;
            
            if (!empId || !month) {
                showMessage('请选择员工和月份', 'error');
                return;
            }
            
            if (!confirm('确定要重新计算该员工的考勤统计吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/summary/rebuild?empId=${empId}&month=${month}`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    currentSummary = result.data;
                    displaySummary(currentSummary);
                    showMessage('统计重新计算成功', 'success');
                } else {
                    showMessage('重新计算失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('重新计算失败: ' + error.message, 'error');
            }
        }
        
        // 导出CSV
        function exportCSV() {
            if (!currentSummary) {
                showMessage('请先查询统计数据', 'error');
                return;
            }
            
            // CSV 内容
            const csvContent = [
                ['考勤统计报表'],
                [],
                ['员工工号', currentSummary.empNo || '-'],
                ['员工姓名', currentSummary.employeeName || '-'],
                ['统计月份', currentSummary.month],
                [],
                ['统计项目', '数值', '单位'],
                ['出勤天数', currentSummary.workDays || 0, '天'],
                ['迟到次数', currentSummary.lateCount || 0, '次'],
                ['早退次数', currentSummary.earlyCount || 0, '次'],
                ['旷工次数', currentSummary.absentCount || 0, '次'],
                ['请假时长', currentSummary.leaveHours || 0, '小时'],
                ['加班时长', currentSummary.otHours || 0, '小时'],
                ['出差天数', currentSummary.travelDays || 0, '天'],
                [],
                ['导出时间', new Date().toLocaleString('zh-CN')]
            ].map(row => row.join(',')).join('\n');
            
            // 添加 BOM 以支持中文
            const BOM = '\uFEFF';
            const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            link.setAttribute('href', url);
            link.setAttribute('download', `考勤统计_${currentSummary.empNo}_${currentSummary.month}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showMessage('CSV文件已导出', 'success');
        }
        
        // 显示消息
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = text;
            messageDiv.className = 'message ' + type;
            
            setTimeout(() => {
                messageDiv.className = 'message';
            }, 3000);
        }
    </script>
</body>
</html>

